import fs from 'fs-extra';
import path from 'path';
import { BaseTask, TaskResult } from '../../common/tasks/BastTask.js';
import { layatoolchain } from '../../layatoolchain.js';
import { toolchain } from '../../toolchain.js';
import { Cmd } from '../../tools/Cmd.js';
import { SSHClient } from '../../tools/SSHClient.js';
import { md5 } from '../../tools/vendor.js';

export class LayaUploadResTask extends BaseTask {
    async run(): Promise<TaskResult<void>> {
        const pfs = this.cmdOption.gameIds.split(/,\s*/);

        // 开发版直接传到本机tomcat
        if (toolchain.params.projectType == 'develop') {
            console.log('copy patch files to local tomcat:', toolchain.params.uploadPath);
            await fs.copy(path.join(layatoolchain.projectFilesRoot(pfs[0], toolchain.params.projectType), 'patch'), toolchain.params.uploadPath);
        } else {
            // 从多个pf中提取不同cdn的进行打包
            for (const pf of pfs) {
                const pfRoot = layatoolchain.projectFilesRoot(pf, toolchain.params.projectType);
                const patchFolder = path.join(pfRoot, 'patch');
                if (!fs.existsSync(patchFolder)) continue;
    
                // 打包
                const tarFile = path.join(pfRoot, 'patch.tgz');
                await new Cmd().run('tar', ['-C', patchFolder, '-czvf', tarFile, '.'], { silent: true });
                // 上传
                await this.upLoadRes(tarFile);
                // commit md5
                const md5FolderPath = layatoolchain.pfPublishRecRoot(this.cmdOption.oldToolsRoot, pf);
                const md5ConfigPath = path.join(md5FolderPath, 'md5.txt');
                toolchain.svnClient.commit('md5@clientbuilder', md5ConfigPath);
            }
        }

        console.log('upload res finished!');
        return { success: true, errorCode: 0 };
    }

    private async upLoadRes(srcResfile: string) {
        const cdn = toolchain.resolveCDN();

        console.log('ready to upload!');
        const dstResfile = `/tmp/${toolchain.params.projectName}_${toolchain.params.projectType}_${this.cmdOption.platform}.tgz`;
        
        const ssh = new SSHClient();
        await ssh.connect(cdn.hostinfo);
        await ssh.exec(`rm ${dstResfile} -f`);
        await ssh.put(srcResfile, dstResfile);

        // 获取远程机器os信息
        const osInfo = await ssh.exec('uname -a');
        let md5cmd = 'md5sum';
        if(osInfo.startsWith('Darwin')) {
            md5cmd = 'md5';
        }

        // 比较文件md5
        const remoteMd5stdout = await ssh.exec(`${md5cmd} ${dstResfile}`);
        const remoteMd5 = remoteMd5stdout.match(/[0-9a-fA-F]{32}/)![0].toLowerCase();
        const localMd5 = md5(fs.readFileSync(srcResfile));
            
        if(remoteMd5 != localMd5) {
            console.error('errer: md5 is not equal!');
            process.exit(1);
        }
        console.log('md5 is equal...');
        
        await ssh.exec(`mkdir -p ${cdn.cdnDir}`);
        await ssh.exec(`tar -xzf ${dstResfile} -C ${cdn.cdnDir}`);
        await ssh.exec(`chmod -R o+rx ${cdn.cdnDir}`);
        await ssh.end();
    }

    get skip(): boolean {
        return !this.cmdOption.uploadRes;
    }
}
